package com.camera2.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.arialyy.aria.core.Aria;
import com.camera2.bean.ApplicationHelper;
import com.camera2.bean.InjuryBean;
import com.camera2.http.GlobalUrl;
import com.camera2.http.SendReply;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class ExpertInjuryDetail extends Activity {
    private static final String TAG = "DeviceWarnList";

    private String message;
    private String ecpertId;

    private InjuryBean bean;

    private ImageView iv_injury;
    private TextView tv_injury;
    private ImageView iv_voice;
    private TextView et_reply;
    private String reply;

    //录音相关
    private MediaRecorder mr;
    private MediaPlayer mp;
    private File voiceDir;
    private File curVoiveFile;
    private Button btStartRecord;
    private Button btStartPlay;
    private ImageView iv;
    private Drawable[] micImages;


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String info = (String) msg.obj;
                    if (info.equals("success")) {
                        Toast.makeText(getApplicationContext(), "提交成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();

                    }
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "连接网络失败,请检查网络是否连接", Toast.LENGTH_SHORT)
                            .show();
                    finish();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.expert_injury_detail);

        iv_injury = findViewById(R.id.iv_injury);
        tv_injury = findViewById(R.id.tv_injury);
        iv_voice = findViewById(R.id.iv_voice);
        et_reply = findViewById(R.id.et_reply);


        iv_voice.setVisibility(View.GONE);
        init();
        initVoice();

    }


    public void init() {
        bean = ((ApplicationHelper) getApplication().getApplicationContext()).getInjuryBean();
        Picasso.with(this).load(GlobalUrl.getMediaUrl() + bean.getImg()).into(iv_injury);
        tv_injury.setText(bean.getDisease());

        ecpertId = bean.getId() + "";
        String voice = bean.getVoice();
        if (!voice.equals("")) {
            Log.i(TAG, "init: "+Environment.getExternalStorageDirectory().getPath() + "/"+ voice);
            Aria.download(this)
                    .load(GlobalUrl.getMediaUrl()+voice)
                    .setDownloadPath(Environment.getExternalStorageDirectory().getPath() +"/"+ voice)
                    .start();
            iv_voice.setVisibility(View.VISIBLE);
        }

    }

    public void submit(View view) {
        reply = et_reply.getText().toString().trim();
        bean.setConclusion(reply);
        ((ApplicationHelper) getApplication().getApplicationContext()).setInjuryBean(bean);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String log = SendReply.send(getApplicationContext());
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = log;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    public void initVoice() {
        voiceDir = new File(Environment.getExternalStorageDirectory(), "xiaomuyi");
        if (!voiceDir.exists()) {
            voiceDir.mkdirs();
        }
        initMediaRecorder();
        initMediaPlayer();

        btStartRecord = findViewById(R.id.button1);

        btStartRecord.setOnLongClickListener(new startRecordListener());
        btStartRecord.setOnClickListener(new stopRecordListener());

        btStartPlay = findViewById(R.id.button3);

        iv = findViewById(R.id.imageView1);
        micImages = new Drawable[]{getResources().getDrawable(R.drawable.record_animate_01),
                getResources().getDrawable(R.drawable.record_animate_02), getResources().getDrawable(R.drawable.record_animate_03),
                getResources().getDrawable(R.drawable.record_animate_04), getResources().getDrawable(R.drawable.record_animate_05),
                getResources().getDrawable(R.drawable.record_animate_06), getResources().getDrawable(R.drawable.record_animate_07),
                getResources().getDrawable(R.drawable.record_animate_08), getResources().getDrawable(R.drawable.record_animate_09),
                getResources().getDrawable(R.drawable.record_animate_10), getResources().getDrawable(R.drawable.record_animate_11),
                getResources().getDrawable(R.drawable.record_animate_12), getResources().getDrawable(R.drawable.record_animate_13),
                getResources().getDrawable(R.drawable.record_animate_14),};
    }

    @SuppressLint("InlinedApi")
    private void initMediaRecorder() {
        mr = new MediaRecorder();
        mr.setAudioSource(MediaRecorder.AudioSource.MIC);
        if (Build.VERSION.SDK_INT > 10) {
            mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        } else {
            mr.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        }
        mr.setOnErrorListener(new MediaRecorder.OnErrorListener() {

            @Override
            public void onError(MediaRecorder mr, int what, int extra) {
            }
        });
        mr.setOnInfoListener(new MediaRecorder.OnInfoListener() {

            @Override
            public void onInfo(MediaRecorder mr, int what, int extra) {
            }
        });

    }

    private void initMediaPlayer() {
        mp = new MediaPlayer();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                btStartPlay.setEnabled(true);
                btStartRecord.setEnabled(true);
            }
        });
        mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                btStartRecord.setEnabled(false);
                btStartPlay.setEnabled(false);
            }
        });
        mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {

            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
    }


    SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd-hh-mm-ss");

    class startRecordListener implements View.OnLongClickListener {
        @Override
        public boolean onLongClick(View v) {
            try {
                initMediaRecorder();
                curVoiveFile = File.createTempFile(sdf.format(new Date()), ".arm", voiceDir);
                System.out.println("nihao" + curVoiveFile.getAbsolutePath());
                SendReply.voicePath = curVoiveFile.getAbsolutePath();
                mr.setOutputFile(curVoiveFile.getAbsolutePath());
                mr.prepare();
                mr.start();
                updateMicStatus();
            } catch (IllegalStateException e) {
                e.printStackTrace();
//                stopRecord(v);
                initMediaRecorder();
            } catch (IOException e) {
                e.printStackTrace();
//                stopRecord(v);
                initMediaRecorder();
            }
            return false;
            //KeyPoint：setOnLongClickListener中return的值决定是否在长按后再加一个短按动作，true为不加短按,false为加入短按
        }
    }

    //短按停止录音，直接点击短按无效
    class stopRecordListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            mr.stop();
            mr.reset();
            mr.release();
            mr = null;
            btStartRecord.setEnabled(true);
            btStartPlay.setEnabled(true);
            mHandler.removeCallbacks(mUpdateMicStatusTimer);
        }
    }

    public void startPlay(View v) {
        if (curVoiveFile == null || !curVoiveFile.exists()) {
            return;
        }
        if (mp == null) {
            initMediaPlayer();
        }
        try {
            mp.setDataSource(curVoiveFile.getAbsolutePath());
            mp.prepare();
            mp.start();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            stopPlay(v);
        } catch (SecurityException e) {
            e.printStackTrace();
            stopPlay(v);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            stopPlay(v);
        } catch (IOException e) {
            e.printStackTrace();
            stopPlay(v);
        }
    }

    public void stopPlay(View v) {
        mp.stop();
        mp.reset();
        mp.release();
        mp = null;
    }

    private final Handler mHandler = new Handler();
    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateMicStatus();
        }
    };
    /**
     * 更新话筒状态
     */
    private int BASE = 150;
    private int SPACE = 100;// 间隔取样时间

    private void updateMicStatus() {
        if (mr != null) {
            int maxAmpl = mr.getMaxAmplitude();
            int ratio = (int) maxAmpl / BASE;
            int db = 0;// 分贝
            if (ratio > 1)
                db = (int) (20 * Math.log10(ratio));
            iv.setImageDrawable(micImages[db / 7]);
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
        }
    }
}
